import Vue from 'vue'
import VueRouter from 'vue-router'

// 注册路由模块
Vue.use(VueRouter);

// 导入组件
import Login from './pages/Login'
import Layout from './pages/Layout'
import ProductList from './pages/product/ProductList'
import Bar from './pages/charts/Bar'
import Pie from './pages/charts/Pie'
import Line from './pages/charts/Line'


// 定义路由规则表
const routes=[
    // 嵌套路由
    {
        path:'/',
        // redirect:'/login'
        component:Layout,
        children:[
            {
                path:'/product-list',
                component:ProductList
            },
            {
                path:'/charts-bar',
                component:Bar
            },
            {
                path:'/charts-pie',
                component:Pie
            },
            {
                path:'/charts-line',
                component:Line
            }
        ]
    }
    ,
    {
        path:'/login',
        component:Login
    }
]

// 解决同一路由地址多次push会报错的问题
const originalPush = VueRouter.prototype.push
VueRouter.prototype.push = function push(location) {
    return originalPush.call(this, location).catch(err => err)
}


// 创建路由对象
const router=new VueRouter({
    routes
});

// 通过路由导航守卫实现登录拦截
router.beforeEach((to, from, next) => {
    //  /login 不需要拦截
    if(to.path!=='/login'){
        // 从本地存储中获取登录凭证
        const token=sessionStorage.getItem('token')
        if(token===''||token===undefined||token===null){
            // 进行页面重定向
            return next('/login')
        }
        // 放行本次路由跳转
        next();
    }
    // 放行本次路由跳转
    next();
})

// 导出路由对象
export default router;